<template>
  <div class="cart-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>购物车</h1>
      <div class="cart-count">共 {{ cartStore.totalCount }} 件商品</div>
    </div>

    <!-- 购物车内容 -->
    <div class="cart-content" v-loading="cartStore.loading">
      <!-- 空购物车状态 -->
      <div v-if="cartStore.items.length === 0" class="empty-cart">
        <div class="empty-icon">🛒</div>
        <div class="empty-text">购物车是空的</div>
        <div class="empty-desc">快去挑选心仪的商品吧</div>
        <el-button type="primary" @click="$router.push('/')">去购物</el-button>
      </div>

      <!-- 购物车列表 -->
      <div v-else class="cart-list">
        <!-- 全选操作栏 -->
        <div class="cart-header">
          <el-checkbox 
            :model-value="isAllSelected" 
            @change="handleSelectAll"
            :indeterminate="isIndeterminate"
          >
            全选
          </el-checkbox>
          <div class="header-actions">
            <el-button 
              type="danger" 
              text 
              @click="handleClearCart"
              :disabled="cartStore.items.length === 0"
            >
              清空购物车
            </el-button>
          </div>
        </div>

        <!-- 商品列表 -->
        <div class="cart-items">
          <div 
            v-for="item in cartStore.items" 
            :key="item.id" 
            class="cart-item"
            :class="{ 'selected': item.selected }"
          >
            <!-- 选择框 -->
            <div class="item-select">
              <el-checkbox 
                :model-value="item.selected" 
                @change="() => cartStore.toggleItemSelection(item.id)"
              />
            </div>

            <!-- 商品图片 -->
            <div class="item-image">
              <img 
                :src="item.product?.image || '/placeholder.svg'" 
                :alt="item.product?.name"
                @error="handleImageError"
              />
            </div>

            <!-- 商品信息 -->
            <div class="item-info">
              <div class="item-name">{{ item.product?.name }}</div>
              <div class="item-desc">{{ item.product?.description || '暂无描述' }}</div>
              <div class="item-price">¥{{ item.price?.toFixed(2) }}</div>
            </div>

            <!-- 数量控制 -->
            <div class="item-quantity">
              <el-input-number
                :model-value="item.quantity"
                @change="(value) => handleQuantityChange(item.id, value)"
                :min="1"
                :max="99"
                size="small"
                controls-position="right"
              />
            </div>

            <!-- 小计 -->
            <div class="item-subtotal">
              ¥{{ ((item.price || 0) * item.quantity).toFixed(2) }}
            </div>

            <!-- 删除按钮 -->
            <div class="item-actions">
              <el-button 
                type="danger" 
                text 
                @click="handleRemoveItem(item.id)"
                :icon="Delete"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>

        <!-- 结算栏 -->
        <div class="cart-footer">
          <div class="footer-left">
            <span class="selected-count">
              已选择 {{ cartStore.selectedItems.length }} 件商品
            </span>
          </div>
          <div class="footer-right">
            <div class="total-price">
              <span class="label">合计：</span>
              <span class="price">¥{{ cartStore.selectedTotalPrice.toFixed(2) }}</span>
            </div>
            <el-button 
              type="primary" 
              size="large"
              @click="handleCheckout"
              :disabled="cartStore.selectedItems.length === 0"
            >
              去结算 ({{ cartStore.selectedItems.length }})
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCartStore } from '@/stores/cart'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'

const router = useRouter()
const cartStore = useCartStore()

// 计算属性
const isAllSelected = computed(() => {
  return cartStore.items.length > 0 && cartStore.items.every(item => item.selected)
})

const isIndeterminate = computed(() => {
  const selectedCount = cartStore.selectedItems.length
  return selectedCount > 0 && selectedCount < cartStore.items.length
})

// 方法
const handleSelectAll = (checked: boolean) => {
  cartStore.toggleAllSelection(checked)
}

const handleQuantityChange = async (itemId: number, quantity: number) => {
  if (quantity && quantity > 0) {
    await cartStore.updateQuantity(itemId, quantity)
  }
}

const handleRemoveItem = async (itemId: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这件商品吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    await cartStore.removeItem(itemId)
  } catch {
    // 用户取消删除
  }
}

const handleClearCart = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空购物车吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    await cartStore.clearCart()
  } catch {
    // 用户取消清空
  }
}

const handleCheckout = () => {
  if (cartStore.selectedItems.length === 0) {
    ElMessage.warning('请选择要结算的商品')
    return
  }
  
  // 跳转到订单确认页面
  router.push('/order/confirm')
}

const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = '/placeholder.svg'
}

// 生命周期
onMounted(() => {
  cartStore.fetchCartItems()
})
</script>

<style scoped>
.cart-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e5e5e5;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 500;
  color: #333;
}

.cart-count {
  color: #666;
  font-size: 14px;
}

.cart-content {
  min-height: 400px;
}

/* 空购物车样式 */
.empty-cart {
  text-align: center;
  padding: 80px 20px;
}

.empty-icon {
  font-size: 80px;
  margin-bottom: 20px;
  opacity: 0.3;
}

.empty-text {
  font-size: 18px;
  color: #333;
  margin-bottom: 10px;
}

.empty-desc {
  color: #666;
  margin-bottom: 30px;
}

/* 购物车列表样式 */
.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #f8f8f8;
  border-radius: 8px;
  margin-bottom: 20px;
}

.cart-items {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
}

.cart-item:hover {
  background-color: #fafafa;
}

.cart-item.selected {
  background-color: #f0f9ff;
}

.cart-item:last-child {
  border-bottom: none;
}

.item-select {
  margin-right: 15px;
}

.item-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
  border-radius: 8px;
  overflow: hidden;
  background: #f5f5f5;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  flex: 1;
  margin-right: 20px;
}

.item-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 5px;
  line-height: 1.4;
}

.item-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  line-height: 1.4;
}

.item-price {
  font-size: 16px;
  color: #ff6700;
  font-weight: 500;
}

.item-quantity {
  margin-right: 20px;
}

.item-subtotal {
  width: 100px;
  text-align: right;
  font-size: 16px;
  font-weight: 500;
  color: #ff6700;
  margin-right: 20px;
}

.item-actions {
  width: 60px;
  text-align: center;
}

/* 结算栏样式 */
.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-top: 20px;
  position: sticky;
  bottom: 20px;
}

.footer-left {
  color: #666;
}

.footer-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.total-price {
  font-size: 18px;
}

.total-price .label {
  color: #333;
}

.total-price .price {
  color: #ff6700;
  font-weight: 600;
  font-size: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .cart-page {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .cart-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .item-image {
    width: 60px;
    height: 60px;
  }
  
  .cart-footer {
    flex-direction: column;
    gap: 15px;
    position: static;
  }
  
  .footer-right {
    width: 100%;
    justify-content: space-between;
  }
}
</style>